import {
	getOssPolicy,
} from '@/api/common.js'
//选择图片
/** opt 
 * 	sourceType
 *  willExpire
 */
export function chooseImage(opt = {}) {
	let that = this
	const {
		sourceType,
		willExpire,
		isFullPath,
		showToast,
		count = 1
	} = opt;
	console.log(count);
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: sourceType || ['album'], //从相册选择
			success: function(res) {
				let filePath = res.tempFilePaths[0]
				resolve(uploadFile(filePath, {
					willExpire,
					isFullPath,
					showToast
				}), filePath)
			},
			fail(res) {
				console.log(res)
			},
		});
	})
}

export function chooseImageWithOrginalFile(opt = {}) {
	let that = this
	const {
		sourceType,
		willExpire,
		isFullPath,
		showToast
	} = opt;
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: sourceType || ['camera'], //从相册选择
			success: function(res) {
				const filePath = res.tempFilePaths[0]
				uploadFile(filePath, {
					willExpire
				}).then((fileUrl) => {
					resolve({
						fileUrl,
						filePath
					})
				})

			},
			fail(res) {
				console.log(res)
			},
		});
	})
}

export function uploadFile(filePath, opt = {}) {
	let that = this
	const {
		type,
		willExpire,
		isFullPath = true,
		showToast = true
	} = opt;
	return new Promise((resolve, reject) => {
		if (showToast) {
			uni.showToast({
				title: '正在上传...',
				icon: 'loading',
				mask: true,
				duration: 10000
			})
		}
		let data = {}
		let promise = null
		if (willExpire) {
			promise = getWillExpirePolicy(data)
		} else {
			promise = getOssPolicy(data)
		}
		let suffix = '.png';
		if (type === 'video') {
			suffix = '.mp4';
		}
		if (typeof filePath === 'string' && !filePath.includes('blob')) {
			suffix = `.${filePath.replace(/.+\./,"")}`.toLowerCase();
		}
		promise.then((res) => {
			if (res.status === 1) {
				let OSSAccessKeyId = res.data.OSSAccessKeyId;
				let callback = res.data.callback;
				let dir = res.data.dir;
				let expire = res.data.expire;
				let host = res.data.host;
				let policy = res.data.policy;
				let signature = res.data.signature;
				let key = dir + new Date().getTime() + suffix;
				uni.uploadFile({
					// 需要上传的地址
					url: host,
					filePath: filePath,
					name: 'file',
					formData: {
						policy: policy, // 输入你获取的的policy
						OSSAccessKeyId, // 输入你的AccessKeyId
						success_action_status: '00000', // 让服务端返回200,不然，默认会返回204
						signature: signature, // 输入你获取的的signature
						key: key
					},
					success(ret) {
						console.log(ret)
						uni.hideToast()
						if (ret.statusCode == 204) {
							if (isFullPath) {
								resolve(host + '/' + key)
							} else {
								resolve({
									path: key,
									fullPath: host + '/' + key
								})
							}
						} else {
							uni.showToast({
								title: ret.errMsg,
								icon: 'none',
							})
						}
					},
					fail(error) {
						reject(error);
					}
				});
			}
		})
	});
}

export async function getUploadParam(filePath, opt = {}) {
	const {
		type,
		willExpire,
		isFullPath = true
	} = opt;
	let data = {}
	let promise = null
	if (willExpire) {
		promise = getWillExpirePolicy(data)
	} else {
		promise = getOssPolicy(data)
	}
	let suffix = '.png';
	if (type === 'video') {
		suffix = '.mp4';
	}
	if (typeof filePath === 'string' && !filePath.includes('blob')) {
		suffix = `.${filePath.replace(/.+\./,"")}`
	}
	const res = await promise.then();
	if (res.status === 1) {
		let OSSAccessKeyId = res.data.OSSAccessKeyId;
		let callback = res.data.callback;
		let dir = res.data.dir;
		let expire = res.data.expire;
		let host = res.data.host;
		let policy = res.data.policy;
		let signature = res.data.signature;
		let key = dir + new Date().getTime() + suffix;
		return {
			url: host,
			filePath: filePath,
			name: 'file',
			formData: {
				policy: policy, // 输入你获取的的policy
				OSSAccessKeyId, // 输入你的AccessKeyId
				success_action_status: '00000', // 让服务端返回200,不然，默认会返回204
				signature: signature, // 输入你获取的的signature
				key: key
			},
			path: key,
			fullPath: host + '/' + key
		}
	} else {
		return null;
	}
}

//选择视频
export function chooseVideo(opt = {}) {
	let that = this
	const {
		sourceType = ['camera'],
		willExpire,
		isFullPath,
		showToast,
		count = 1
	} = opt;
	console.log(count);
	return new Promise((resolve, reject) => {
		uni.chooseVideo({
			compressed: false,
			sourceType,
			maxDuration: 60,
			camera: 'back',
			count,
			success(res) {
				let filePath = res.tempFilePath;
				resolve(uploadFile(filePath, {
					type: 'video',
					willExpire,
					isFullPath,
					showToast
				}))
			}
		})
	})
}

//获取图片的宽和高
export function getImgInfo(url) {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: url,
      success: (info) => {
        resolve(info); // 成功时将info传递给resolve
      },
      fail: (e) => {
        reject(e); // 失败时将错误信息传递给reject
      },
    });
  });
}
//获取视频的宽和高
export function getVideoInfo(url) {
  return new Promise((resolve, reject) => {
    uni.getVideoInfo({
      src: url,
      success: (info) => {
        resolve(info); // 成功时将info传递给resolve
      },
      fail: (e) => {
        reject(e); // 失败时将错误信息传递给reject
      },
    });
  });
}
export default {
	chooseImage: chooseImage,
	chooseVideo: chooseVideo,
	chooseImageWithOrginalFile: chooseImageWithOrginalFile,
	uploadFile: uploadFile,
	getImgInfo:getImgInfo,
	getVideoInfo:getVideoInfo,
}
